package cn.lvhang.pay.controller;

import cn.lvhang.order.constants.OrderConstants;
import cn.lvhang.order.domain.AdoptOrder;
import cn.lvhang.order.service.IAdoptOrderService;
import cn.lvhang.pay.constants.AlipayConfig;
import cn.lvhang.pay.constants.PayConstants;
import cn.lvhang.pay.domain.AlipayInfo;
import cn.lvhang.pay.domain.PayBill;
import cn.lvhang.pay.service.IAlipayInfoService;
import cn.lvhang.pay.service.IPayBillService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private IAdoptOrderService adoptOrderService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request){

        //获取支付宝POST过来反馈信息
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                params.put(name, valueStr);
            }
            String unionPaySn = params.get("out_trade_no");
            PayBill bill = payBillService.loadByUnionPaySn(unionPaySn);
            if(bill != null) {
                AlipayInfo info = alipayInfoService.getByShopId(bill.getShop_id());
                //验证签名
                boolean signVerified = AlipaySignature.rsaCheckV1(
                        params,
                        info.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名
                if (signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no = request.getParameter("out_trade_no");
                    //支付宝交易号
                    String trade_no = request.getParameter("trade_no");
                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if (trade_status.equals("TRADE_FINISHED")) {

                    } else if (trade_status.equals("TRADE_SUCCESS")) {
                        //1.改支付单状态
                        bill.setState(1);
                        bill.setUpdateTime(new Date());
                        payBillService.update(bill);
                        //2.记录流水
                        //3.修改业务库的业务订单状态
                        if(PayConstants.BUSINESS_TYPE_ADOPT.equals(bill.getBusinessType())){
                            AdoptOrder order = adoptOrderService.queryById(bill.getBusinessKey());
                            order.setState(1);
                            adoptOrderService.update(order);
                        }else if(PayConstants.BUSINESS_TYPE_PRODUCT.equals(bill.getBusinessType())){

                        }
                    }
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.@TODO 支付成功之后取消定时任务
    }
}
